<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" ref="queryForm">
        <el-form-item label="课程名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入课程名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="课程状态" label-width="80px">
          <el-select v-model="queryParams.status" placeholder="课程状态" clearable   style="width: 150px;" >
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
            <el-option label="全部" value="" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <el-card class="table-container">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">新增课程</el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="courseList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="课程名称" prop="title" />
        <el-table-column label="课程封面" width="100">
          <template #default="{ row }">

            <el-image
              :src="row.coverImage"
              :preview-teleported=true
              :preview-src-list="[row.coverImage]"
              fit="cover"
              class="course-cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="课程价格" prop="price" width="100">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="讲师" prop="teacherName" width="120" />
        <el-table-column label="课程状态" prop="status" width="100">
          <template #default="{ row }">
            <StatusTag :status="row.status" type="course" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button
              link
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="700px"
      append-to-body
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程封面" prop="coverUrl">
          <el-upload
            class="cover-uploader"
            :action="'/upload/course-cover'"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
          >
            <img
              v-if="courseForm.coverUrl"
              :src="courseForm.coverUrl"
              class="cover"
              @error="handleImageError"
              @load="handleImageLoad"
            />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>

        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input-number
            v-model="courseForm.price"
            :precision="2"
            :step="0.01"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="课程讲师" prop="teacherId">
          <el-select v-model="courseForm.teacherId" placeholder="请选择讲师">
            <el-option
              v-for="item in teacherOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入课程简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {getCourseList, addCourse, updateCourse, deleteCourse, toggleCourseStatus, upload} from '@/api/course'
import { getTeacherOptions } from '@/api/teacher'


// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ""
})

// 数据列表
const courseList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 教师选项
const teacherOptions = ref([])

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单对象
const courseForm = reactive({
  id: undefined,
  name: '',
  coverUrl: '',
  price: 0,
  teacherId: undefined,
  description: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  coverUrl: [
    { required: true, message: '请上传课程封面', trigger: 'change' }
  ],
  teacherId: [
    { required: true, message: '请选择课程讲师', trigger: 'change' }
  ]
}

// 文件上传配置 fixme 废弃
// const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/upload'

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    await getCourseList(queryParams.value).then(res =>{
      courseList.value = res.data.records
      total.value = res.data.total
      console.log(courseList.value)
    })
    Object.keys(courseForm).forEach(key => {
      courseForm[key] = undefined
    })



  } catch (error) {
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}


// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 上传图片
// const HandlerUpload = async () =>{
//   upload()
// }

// 新增课程
const handleAdd = async () => {
  dialog.title = '新增课程'
  dialog.visible = true
  courseForm.id = undefined
  courseForm.name = ''
  courseForm.coverUrl = ''
  courseForm.price = 0
  courseForm.teacherId = undefined
  courseForm.description = ''

  // 获取教师选项
  try {
    const { data } = await getTeacherOptions()
    teacherOptions.value = data
  } catch (error) {
    console.error('获取教师列表失败:', error)
  }
}

// 编辑课程
const handleEdit = async (row) => {
  const { data } = await getTeacherOptions()
  teacherOptions.value = data

  dialog.title = '编辑课程'
  dialog.visible = true
  Object.assign(courseForm, row)
}

// 提交表单
const submitForm = async () => {
  try {
    if (courseForm.id) {
      await updateCourse(courseForm)
      ElMessage.success('修改成功')
    } else {
      await addCourse(courseForm)
      ElMessage.success('新增成功')
    }
    dialog.visible = false
    getList()
  } catch (error) {
    console.error('保存课程失败:', error)
  }
}

// 删除课程
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该课程吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCourse(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除课程失败:', error)
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的课程')
    return
  }
  ElMessageBox.confirm(`确认要删除选中的 ${selectedIds.value.length} 个课程吗？`, '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCourse(selectedIds.value)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
    }
  })
}

// 切换课程状态
const handleToggleStatus = async (row) => {
  try {
    await toggleCourseStatus(row.id)
    ElMessage.success('操作成功')
    getList()
  } catch (error) {
    console.error('切换状态失败:', error)
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    courseForm.coverUrl = response.data
    ElMessage.success('封面上传成功！')
  } else {
    ElMessage.error('上传失败：' + (response.msg || '未知错误'))
  }
}

// 上传失败回调
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('封面上传失败，请重试')
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  ElMessage.warning('图片加载失败，请检查网络连接')
}

// 图片加载成功处理
const handleImageLoad = (event) => {
  console.log('图片加载成功:', event.target.src)
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>


.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    .card-header {
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }
  }

  .course-cover {
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }

  .cover-uploader {
    .cover {
      width: 148px;
      height: 148px;
      display: block;
    }

    .cover-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      //overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
